package server;

import java.util.ArrayList;
import java.util.Random;
/**
 * A class which handles the nounce function.
 * @author dt08sj7
 */
public class NounceHandler {
	private final ArrayList<String> generated;
	private final ArrayList<String> used;
	private final Random random;
/**
 * Creates a new nounce handler.
 */
	public NounceHandler() {
		generated = new ArrayList<String>();
		used = new ArrayList<String>();
		random = new Random();

	}

	/**
	 * Generates a new nounce and add it to a list.
	 * @return
	 * 			return a string with the nounce.
	 */

	public String getNewNounce() {
		int nounce = generateNewNounce();
		generated.add("" + nounce);

		return "" + nounce;
	}
	/**
	 * Generates a unique nounce.
	 * @return
	 *			a int with the nounce
	 */
	 private int generateNewNounce() {
		int nounce;
		do {
			nounce = random.nextInt();

		} while (alreadyCreated("" + nounce));

		return nounce;
	}
	 /**
	  * Controls if the nounce already has been used.
	  * @param nounce
	  * 			the nounce to control.
	  * @return
	  * 		true if the nounce has been used before.
	  */
	private boolean alreadyUsed(String nounce) {

		return used.contains(nounce);

	}
	/**
	 * Controls if the nounce already has been created.
	 * @param nounce
	 * 				the nounce to control.
	 * @return
	 * 			true if the nounce has been created.
	 */
	private boolean alreadyCreated(String nounce) {
		return generated.contains(nounce);
	}
	/**
	 * Validates the nounce.
	 * @param nounce
	 * 			the nounce to be validated.
	 * @return
	 *			true if the nounce is valid.
	 */
	public boolean validateNounce(String nounce) {
		if (alreadyUsed(nounce)) {
			return false;

		} else if (alreadyCreated(nounce)) {
			used.add(nounce);
			return true;

		}
		return false;

	}

}
